# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 15:11:58 2018

@author: cm
"""

from flask import Flask, jsonify, request, render_template
import pymysql
import pandas as pd
import numpy as np

app = Flask(__name__)
#app.config['JSON_AS_ASCII'] = False
# 返回结果


def sql1(t):
    conn = pymysql.connect(host="localhost",
                           user="root", password="cp9595",
                           db='wzry', port=3306)
    cur = conn.cursor()
    cur = conn.cursor()
    cur.execute(t)
    result = cur.fetchall()
    conn.commit()
    cur.close()
    return result


def pandas_df_json(data):
    columns = data.columns
    json_all = [dict(zip(columns, np.array(data.ix[i, :])))
                for i in range(len(data))]
    return json_all


# 首页
@app.route("/", methods=["POST", "GET"])
def index():
    return render_template("index.html")


# 英雄技能
hero_skill_sql = '''
                    select name,concat("<img src = 'https:",skill_img,"' height='34' width='34' /> ") skill_img,
                    skill_name,skill_cold,skil_cost,skill_desc
                    from d2  a
                    where a.name =  %s
                    and skill_desc <> ''
                '''
hero_exist_sql_2 = 'select name from d2 where name = %s '


@app.route("/skill", methods=["POST", "GET"])
def skill():
    if request.method == "POST":
        flag = request.form.get("flag", "null")
        flag = str(flag)
        print(flag)
        hero_exists = sql1(hero_exist_sql_2 % ("'" + flag + "'"))
        if len(hero_exists) > 0:
            data_temp = sql1(hero_skill_sql % ("'" + flag + "'"))
            data_temp = pd.DataFrame(
                list(data_temp),
                columns=[
                    'hero',
                    'skill',
                    'skill_name',
                    'cold',
                    'consume',
                    'desc'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data'], [data_temp]))
            return jsonify(data)
        else:
            data_temp = pd.DataFrame({'hero': '',
                                      'skill': '',
                                      'skill_name': '',
                                      'cold': '',
                                      'consume': '',
                                      'desc': ''},
                                     index=[0],
                                     columns=['hero',
                                              'skill',
                                              'skill_name',
                                              'cold',
                                              'consume',
                                              'desc'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data', 'name'], [data_temp, '该英雄人物不存在！']))
            return jsonify(data)
    else:
        return render_template("skill.html")


# 英雄皮肤
hero_skin_sql = '''
                 select name,skin_name,concat("<img src = 'https:",skin_src,"' height='340' width='540' /> ") skill_img
                 from d4  a   where a.name =  %s
                '''
hero_exist_sql_4 = 'select name from d4 where name = %s '


@app.route("/skin", methods=["POST", "GET"])
def skin():
    if request.method == "POST":
        flag = request.form.get("flag", "null")
        flag = str(flag)
        hero_exists = sql1(hero_exist_sql_4 % ("'" + flag + "'"))
        if len(hero_exists) > 0:
            data_temp = sql1(hero_skin_sql % ("'" + flag + "'"))
            data_temp = pd.DataFrame(
                list(data_temp), columns=[
                    'hero', 'skinname', 'skin_pic'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data'], [data_temp]))
            return jsonify(data)
        else:
            data_temp = pd.DataFrame({'hero': '', 'skinname': '', 'skin_pic': ''},
                                     index=[0], columns=['hero', 'skinname', 'skin_pic'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data', 'name'], [data_temp, '该英雄人物不存在！']))
            return jsonify(data)
    else:
        return render_template("skin.html")


# 推荐符文
recomm_sql = '''
                 select name,concat("<img src = 'https:",mw_img,"' height='34' width='34' /> ") skill_img,
                 mw_desc,mw_tips
                 from d3  a   where a.name =  %s
                '''
hero_exist_sql_3 = 'select name from d3 where name = %s '


@app.route("/recomm", methods=["POST", "GET"])
def recomm():
    if request.method == "POST":
        flag = request.form.get("flag", "null")
        flag = str(flag)
        hero_exists = sql1(hero_exist_sql_3 % ("'" + flag + "'"))
        if len(hero_exists) > 0:
            data_temp = sql1(recomm_sql % ("'" + flag + "'"))
            data_temp = pd.DataFrame(
                list(data_temp), columns=[
                    'hero', 'pic', 'desc', 'tips'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data'], [data_temp]))
            return jsonify(data)
        else:
            data_temp = pd.DataFrame({'hero': '', 'pic': '', 'desc': '', 'tips': ''},
                                     index=[0], columns=['hero', 'pic', 'desc', 'tips'])
            data_temp = pandas_df_json(data_temp)
            data = dict(zip(['data', 'name'], [data_temp, '该英雄人物不存在！']))
            return jsonify(data)
    else:
        return render_template("recomm.html")


if __name__ == "__main__":
    app.run('0.0.0.0', port=8888)
